const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

exports.main = async (event, context) => {
  try {
    // 1. 解构参数
    const {
      title,
      time,
      location,
      detail,
      talk,
      latitude,
      longitude,
      pic,  // 接收云文件ID
      publisher,
      publisher_id
    } = event

    // 2. 生成带签名的临时URL
    const { fileList } = await cloud.getTempFileURL({
      fileList: [pic]
    })
    const picUrl = fileList[0].tempFileURL

    // 3. 写入数据库
    const db = cloud.database()
    const result = await db.collection('actives').add({
      data: {
        title,
        time,
        location,
        detail,
        talk,
        latitude,
        longitude,
        pic: picUrl,  // 存储带签名的URL
        publisher,
        publisher_id,
        createTime: cloud.database().serverDate(),
      }
    })

    return {
      code: 0,
      data: result,
      message: '活动创建成功'
    }
  } catch (err) {
    console.error(err)
    return {
      code: -1,
      message: '活动创建失败: ' + err.message
    }
  }
}